package com.cta.view.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import com.cta.entity.Site;
import com.cta.service.SiteService;
import com.cta.view.json.SiteNodeJson;

@Controller
public class SiteController extends BasicController implements InitializingBean, ServletContextAware {
	
	private static final String EDIT_MODE = "edit";
	private static final String NEW_MODE = "new";
	@Autowired
	private SiteService siteService;

	@Autowired
	private MessageSource messageSource;

	private ServletContext servletContext;

	@RequestMapping(value = "/create-site", method = RequestMethod.POST)
	@ResponseBody
	public String createSite(Locale locale, String name, String description, Long id, String mode) {
		try {
			if (NEW_MODE.equals(mode)) {
				Site site = siteService.createSite(name, description, id);
				return String.format("{'success':true, msg:'%s', id: %s}", messageSource.getMessage("site.create.message.success", null, locale), site.getId());
			} else if(EDIT_MODE.equals(mode)){
				siteService.updateSite(id, name, description);
				return String.format("{'success':true, msg:'%s'}", "Edit successful");
			}
			return String.format("{'success':false, msg:'%s'}", "Fail Command");
		} catch (Exception e) {
			log.error("Error: ", e);
			return String.format("{'success':false, msg:'%s'}", messageSource.getMessage("site.create.message.fail", null, locale));
		}
	}

	@RequestMapping(value = "/tree-view", method = RequestMethod.GET)
	@ResponseBody
	public List<SiteNodeJson> treeView(Locale locale, @RequestParam(value = "node", required = true) Long parentId) {
		try {
			List<Site> allChildSite = siteService.findAllChildSite(parentId);
			List<SiteNodeJson> results = new ArrayList<SiteNodeJson>(allChildSite.size());
			for (Site site : allChildSite) {
				if(site.getParentId() != null && site.getParentId() != 0){
					results.add(new SiteNodeJson(String.valueOf(site.getId()), site.getName(), site.getDescription(), "icon-not-leaf-organization", false));
				} else {
					results.add(new SiteNodeJson(String.valueOf(site.getId()), site.getName(), site.getDescription(), "icon-leaf-organization", true));
				}
			}
			return results;
		} catch (Exception e) {
			log.error("Error: ", e);
			return new ArrayList<SiteNodeJson>();
		}
	}

	@RequestMapping(value = "/check-site-name", method = RequestMethod.GET)
	@ResponseBody
	public String checkName(Locale locale, String value) {
		try {
			Site site = siteService.findSiteByName(value);
			if(site == null) {
				return "{'success':true}";
			} else {
				return String.format("{'success':false, msg:'%s'}", messageSource.getMessage("site.check-name.duplicate", null, locale));
			}
		} catch (Exception e) {
			log.error("Error: ", e);
			return String.format("{'success':false, msg:'%s'}", messageSource.getMessage("site.check-name.fail", null, locale));
		}
	}
	
	public void afterPropertiesSet() throws Exception {
		// init root node
		Site site = siteService.findRootSite();
		if (site == null) {
			site = siteService.createSite("Organization", "Root Tree", null);
		}
		this.servletContext.setAttribute("rootNode", String.format("{name: '%s', id: %s, allowDrop: false, expanded: true, description: '%s',  iconCls:'icon-root-organization'}", site.getName(), site.getId(), site.getDescription()));
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
